<script setup lang="ts">
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './util/source.data';
  import { MessageSource } from '@/api/resource/resourceAllApi';
  import { SelectGroupItem } from '@/api/resource/model/resourceAllModel';

  const { addOrUpdate, queryAllByCloud, scriptAllByCloud, queryAllByTarget } = MessageSource();
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 12 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    const allCloudSource = await queryAllByCloud(data.record);
    const allCloudScript: Map<string, SelectGroupItem[]> = await scriptAllByCloud(
      data.record.cloudOption,
    );
    const idScript = allCloudScript['1007001'];
    const pushPreScript = allCloudScript['1007004'];
    const databasePreScript = allCloudScript['1007005'];
    const targetIdOptions = await queryAllByTarget();
    updateSchema([
      {
        field: 'targetId',
        componentProps: { options: targetIdOptions },
      },
      {
        field: 'parentId',
        componentProps: { options: allCloudSource },
      },
      {
        field: 'keyScriptId',
        componentProps: { options: idScript },
      },
      {
        field: 'pushPreScript',
        componentProps: { options: pushPreScript },
      },
      {
        field: 'databasePreScript',
        componentProps: { options: databasePreScript },
      },
    ]);
    setFieldsValue({
      ...data.record,
    });
  });
  const getTitle = computed(() => (!unref(isUpdate) ? '新增脚本' : '编辑脚本'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      await addOrUpdate(values);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>

<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="70%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
